﻿using CommonEntity.CommonImageEntities;
using Grpc.Core;
using ImageDomain.Agg;
using ImageDomain.Utils;
using Newtonsoft.Json;
using ScienceRpcServe.Protos;
using ScienceRpcServe.Utils;
using Point3d = CommonEntity.CommonImageEntities.Point3d;

namespace ScienceRpcServe.Services;

public class ImageShowService : ImageShow.ImageShowBase
{
    private readonly ILogger<ImageShowService> _logger;
    private readonly IArmBoneSegAgg _agg;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="logger"></param>
    /// <param name="agg"></param>
    public ImageShowService(ILogger<ImageShowService> logger, IArmBoneSegAgg agg)
    {
        _logger = logger;
        _agg = agg;
    }

    /// <summary>
    /// 主动设置 dicom序列路径
    /// </summary>
    /// <param name="request"></param>
    /// <param name="context"></param>
    /// <returns></returns>
    public override async Task<BoolResponse> SetDicomFiles(StringRequest request, ServerCallContext context)
    {
        try
        {
            _logger.LogInformation($"{nameof(SetDicomFiles)} | request: {JsonConvert.SerializeObject(request)}");
            await _agg.LoadOriginImageByDir(request.Value);
            return new BoolResponse() { IsSuccess = true };
        }
        catch (Exception e)
        {
            _logger.LogError($"{nameof(SetDicomFiles)} | {JsonConvert.SerializeObject(e)}");
            return new BoolResponse() { IsSuccess = false };
        }
    }

    /// <summary>
    /// 主动设置 dicom序列路径
    /// </summary>
    /// <param name="request"></param>
    /// <param name="context"></param>
    /// <returns></returns>
    public override async Task<BoolResponse> SetItkFile(StringRequest request, ServerCallContext context)
    {
        try
        {
            _logger.LogInformation($"{nameof(SetItkFile)} | request: {JsonConvert.SerializeObject(request)}");
            await _agg.LoadOriginImage(request.Value);
            return new BoolResponse() { IsSuccess = true };
        }
        catch (Exception e)
        {
            _logger.LogError($"{nameof(SetItkFile)} | {JsonConvert.SerializeObject(e)}");
            return new BoolResponse() { IsSuccess = false };
        }
    }

    /// <summary>
    /// 主动设置 dicom序列路径
    /// </summary>
    /// <param name="request"></param>
    /// <param name="context"></param>
    /// <returns></returns>
    public override async Task<BoolResponse> SetNiiGzFile(SetGzFileRequest request, ServerCallContext context)
    {
        try
        {
            _logger.LogInformation($"{nameof(SetNiiGzFile)} | request: {JsonConvert.SerializeObject(request)}");

            if (!File.Exists(request.OriginGzFile)) throw new Exception("nii.gz文件不存在");
            await _agg.LoadOriginImage(request.OriginGzFile);
            await _agg.LoadLabelsImage(request.SegGzFile);
            return new BoolResponse() { IsSuccess = true };
        }
        catch (Exception e)
        {
            _logger.LogError($"{nameof(SetNiiGzFile)} | {JsonConvert.SerializeObject(e)}");
            return new BoolResponse() { IsSuccess = false };
        }
    }

    /// <summary>
    /// 图像获取 -- 这个方法需要好好测试一下
    /// </summary>
    /// <param name="request"></param>
    /// <param name="context"></param>
    /// <returns></returns>
    public override async Task<MatSetResponse> GetMats(MatRequest request, ServerCallContext context)
    {
        try
        {
            _logger.LogInformation($"{nameof(GetMats)} | request: {JsonConvert.SerializeObject(request)}");
            if (_agg.CtImage == null) throw new Exception("尚未采集图像");
            return await _agg.ToMatSetResponse(request.Index, request.Orientation);
        }
        catch (Exception e)
        {
            _logger.LogError($"{nameof(GetMats)} | {JsonConvert.SerializeObject(e)}");
            return new MatSetResponse();
        }
    }


    /// <summary>
    /// 获取图像信息
    /// </summary>
    /// <param name="request"></param>
    /// <param name="context"></param>
    /// <returns></returns>
    public override async Task<ImageInfoResponse> GetImageInfo(EmptyRequest request, ServerCallContext context)
    {
        try
        {
            _logger.LogInformation($"{nameof(GetImageInfo)} | {JsonConvert.SerializeObject(request)}");
            return await _agg.ToImageInfoResponse();
        }
        catch (Exception ex)
        {
            _logger.LogError($"{nameof(GetImageInfo)} | {JsonConvert.SerializeObject(ex)}");
            return new ImageInfoResponse() { Remark = ex.Message };
        }
    }

    /// <summary>
    /// 获取tag  todo 优化
    /// </summary>
    /// <param name="request"></param>
    /// <param name="context"></param>
    /// <returns></returns>
    public override async Task<TagInfoResponse> GetTagInfo(EmptyRequest request, ServerCallContext context)
    {
        try
        {
            _logger.LogInformation($"{nameof(GetTagInfo)} | {JsonConvert.SerializeObject(request)}");
            var tags = await _agg.ToTagInfoResponse();
            return tags;
        }
        catch (Exception e)
        {
            _logger.LogError($"{nameof(GetTagInfo)} | {JsonConvert.SerializeObject(e)}");
            return new TagInfoResponse() {Remark = e.Message};
        }

    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="request"></param>
    /// <param name="context"></param>
    /// <returns></returns>
    public override async Task<BoolResponse> AdjustWindow(WindowCenterAndWidthRequest request,
        ServerCallContext context)
    {
        try
        {
            _logger.LogInformation($"{nameof(AdjustWindow)} | request: {JsonConvert.SerializeObject(request)}");
            _agg.CtImage.SetWindowWidthCenter(request.WindowMin, request.WindowMax);
            return new BoolResponse() { IsSuccess = true };
        }
        catch (Exception e)
        {
            _logger.LogError($"{nameof(AdjustWindow)} | {JsonConvert.SerializeObject(e)}");
            return new BoolResponse() { IsSuccess = false };
        }
    }

    public override async Task<IntResponse> GetCtVal(PointRequest request,
        ServerCallContext context)
    {
        try
        {
            _logger.LogInformation($"{nameof(GetCtVal)} | request: {JsonConvert.SerializeObject(request)}");
            if(_agg.CtImage == null) return new IntResponse(){Remark = "请先采集图像"};

            var val = ImageHandler.Instance.GetPixel(_agg.CtImage!, new Point3d() { X = request.Point.X, Y = request.Point.Y, Z = request.Point.Z});
            return new IntResponse() { Value = val };
        }
        catch (Exception e)
        {
            _logger.LogError($"{nameof(GetCtVal)} | {JsonConvert.SerializeObject(e)}");
            return new IntResponse() { Remark = "CT值获取失败"};
        }
    }

}
